package biz

import (
	"log"
	"os"

	cfunc "go-new-project/tools/cfunc"
)

type Install struct {
	path
}

// Install
/**
 *  @Author: rym 2024-01-16 16:39:29
 *  @Description:安装
 *  @receiver i
 */
func (i *Install) Install() {
	i.GetPath()

	i.mkdirChildDir()

	i.createMain()

	i.createGoMod()

	i.writeConfFile()
}

// createMain
/**
 *  @Author: rym 2024-01-16 16:39:36
 *  @Description:创建主函数
 *  @receiver i
 */
func (i *Install) createMain() {
	file := i.Dir + i.Splitter + "main.go"
	content := "package main\n\nfunc main() {\n\n}"

	err := cfunc.CWFile(file, content)
	if err != nil {
		log.Fatal("创建主函数文件失败,请检查权限后重试")
	}
}

// createGoMod
/**
 *  @Author: rym 2024-01-16 16:39:53
 *  @Description:创建包管理
 *  @receiver i
 */
func (i *Install) createGoMod() {
	cmd := "cd " + i.Dir + " && go mod init " + i.AppName

	cfunc.ExecShell(cmd)
}

// mkdirChildDir
/**
 *  @Author: rym 2024-01-16 16:40:00
 *  @Description:创建子目录
 *  @receiver i
 */
func (i *Install) mkdirChildDir() {
	var (
		list []string
		err  error
	)

	list = []string{
		"bin",
		"biz",
		"conf",
		"conf" + i.Splitter + "build",
		"docs",
		"route",
		"test",
		"tools",
	}

	for y := 0; y < len(list); y++ {
		dir := i.Dir + i.Splitter + list[y]
		_, err = os.Stat(dir)
		if err != nil {
			err = os.MkdirAll(dir, 0766)
			if err != nil {
				log.Fatal("自动创建子目录失败，请检查权限后重试")
			}
		}
	}
}

// writeConfFile
/**
 *  @Author: rym 2024-01-16 16:40:11
 *  @Description:创建默认配置文件
 *  @receiver i
 */
func (i *Install) writeConfFile() {
	file := i.Dir + i.Splitter + "Conf/conf.go"
	content := `package conf

import (
	"embed"
	"log"
	"strings"

	xdf "comm-tools-pkg/funcs"
)

const confDir = "build"

type Config struct{}

var Conf Config

//go:embed build
var f embed.FS

func init() {
	_, err := f.ReadDir(confDir)
	if err != nil {
		log.Fatal("NewConf:", err)
	}
}

func (c *Config) Get(v string) string {
	var (
		err      error
		confPath []string
		jsonByte []byte
	)

	confPath = strings.Split(v, "/")

	if len(confPath) < 2 {
		//获取文件的字符串表示形式，如果不存在则返回错误：
		jsonByte, err = f.ReadFile(confDir + "/conf.json")
	} else {
		//获取文件的字符串表示形式，如果不存在则返回错误：
		jsonByte, err = f.ReadFile(confDir + "/" + confPath[0] + ".json")
	}

	if err != nil {
		return ""
	}

	return xdf.ReadJson(confPath, jsonByte)
}`

	err := cfunc.CWFile(file, content)
	if err != nil {
		log.Fatal("创建默认配置文件失败,请检查权限后重试")
	}

	file = i.Dir + i.Splitter + "Conf/build/conf.json"
	content = `{
  "Env":"dev",
  "AppName": "` + i.AppName + `",
  "AppAddr": ":"` + i.Port + `"
}`

	err = cfunc.CWFile(file, content)
	if err != nil {
		log.Fatal("创建默认json配置文件失败,请检查权限后重试")
	}
}
